﻿using System;
using System.Text;

namespace BodaNetCommunications.Utilities.DataLibs
{
    public class StringLib
    {
        public static string GetStringFromByteArrayByBitConvert(byte[] source, int start, int count)
        {
            return BitConverter.ToString(source, start, count);
        }

        public static string GetStringFromByteArray(byte[] source, int start, int count, Encoding encoding)
        {
            return encoding.GetString(ByteArrayLib.GetByteArray(source, start, count));
        }

        public static string GetStringFromByteArray(byte[] source, int start, int count)
        {
            return Encoding.ASCII.GetString(ByteArrayLib.GetByteArray(source, start, count));
        }

        public static string GetHexStringFromByteArray(byte[] source, int start, int count, char segment = ' ')
        {
            byte[] byteArray = ByteArrayLib.GetByteArray(source, start, count);
            StringBuilder stringBuilder = new StringBuilder();
            if (byteArray.Length != 0)
            {
                byte[] array = byteArray;
                foreach (byte b in array)
                {
                    if (segment == '\0')
                    {
                        stringBuilder.Append($"{b:X2}");
                    }
                    else
                    {
                        stringBuilder.Append($"{b:X2}{segment}");
                    }
                }
            }

            if (segment != 0 && stringBuilder.Length > 1 && stringBuilder[stringBuilder.Length - 1] == segment)
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
            }

            return stringBuilder.ToString();
        }

        public static string GetHexStringFromByteArray(byte[] source, char segment = ' ')
        {
            return GetHexStringFromByteArray(source, 0, source.Length, segment);
        }

        public static string GetSiemensStringFromByteArray(byte[] source, int start, int length)
        {
            byte[] byteArray = ByteArrayLib.GetByteArray(source, start, length + 2);
            int num = byteArray[1];
            if (num > 0)
            {
                return Encoding.GetEncoding("GBK").GetString(ByteArrayLib.GetByteArray(byteArray, 2, num));
            }

            return "empty";
        }
    }
}